<?php
/*
*All rights reserved: Json.
*Links:http://www.liyaoquan.cn.
*Links:http://imarkchina.cn.
*Links:http://www.imarkchina.cn.
*/

/**
 * 博客后台连接模型，负责数据，增，删，改，查
 * 因为没有博客数据没使用数据库，所以没有继承 Model 类
 */
Class GetlinksModel extends PublicModel{

	/**
	 * 首页数据处理
	 */
	Public function Show(){
		$file = loadfile(C('link.id'));
		$pageurl = U('index', '', true);
		$indexpage = 12;
		$count = count($file);
		$page = new Page($count, $indexpage, $pageurl);
		$pnum = explode(',', $page->limit());
		$data = array();
		$i = -1;
		foreach ($file as $v => $k) {
			$i++;
			if ($i < $pnum[0] || $i >= $pnum[0] + $pnum[1]) continue;
			$data[] = unfile(C('link.data').$v.'.Mark');
		}
		$redata['link'] = $data;
		$redata['page'] = $page->view();
		return $redata;
	}

	/**
	 * 保存链接数据操作
	 * @param [type] $data  [description]
	 * @param [type] $check [description]
	 */
	Public function SaveData($data, $check){
		$file = loadfile(C('link.id'));
		if ($check) {
			$file[$data['file']] = $data['ord'];
			uasort($file, 'page_sort');
			unset($data['times']);
			if (serfile(C('link.data').$data['file'].'.Mark', $data) && varfile(C('link.id'), $file)) {
				return true;
			}
		} else {
			if (empty($data['file'])) {
				$data['file'] = randCode(6);
				if (file_exists(C('link.data').$data['file'].'.Mark')) {
					$data['file'] = randCode(6);
				}
			}
			$file[$data['file']] = $data['ord'];
			uasort($file, 'page_sort');
			$data['date'] = date('Y.m.d');
			$data['time'] = date('H:s:i', time());
			if (serfile(C('link.data').$data['file'].'.Mark', $data) && varfile(C('link.id'), $file)) {
				return true;
			}
		}
	}

	/**
	 * 删除与更新排序数据处理
	 * @param  [type] $data  [description]
	 * @param  [type] $check [description]
	 * @return [type]        [description]
	 */
	Public function upAnddeSet($data, $check){
		$file = loadfile(C('link.id'));
		if ($check) {
			foreach ($data as $k => $v) {
				foreach ($file as $c => $b) {
					if ($k == $c) {
						$file[$c] = $v;
						$linkfile = unfile(C('link.data').$k.'.Mark');
						$linkfile['ord'] = $v;
						if (!serfile(C('link.data').$k.'.Mark', $linkfile)) {
							return false;
						}
					}
				}
			}
			uasort($file, 'page_sort');
			if (varfile(C('link.id'), $file)) {
				return true;
			}
		} else {
			foreach ($data as $k => $v) {
				foreach ($file as $z => $a) {
					if ($v == $z) {
						unset($file[$v]);
						if (!unlink(C('link.data').$v.'.Mark')) {
							return false;
						}
					}
				}
			}
			uasort($file, 'page_sort');
			if (varfile(C('link.id'), $file)) {
				return true;
			}
		}
	}

	/**
	 * 删除单个链接数据处理
	 * @param [type] $id [description]
	 */
	Public function DelOney($id){
		$file = loadfile(C('link.id'));
		unset($file[$id]);
		uasort($file, 'page_sort');
		if (varfile(C('link.id'), $file) && unlink(C('link.data').$id.'.Mark')) {
			return true;
		}
	}
}